<template>
	<div class="w-screen-sm mx-auto my-lg">
		<h6 @click="back" class="cursor-pointer my-sm">
			<Icon type="md-arrow-back" />返回上一页
		</h6>
		<h1>创建单个NFT</h1>
		<h3 class="my-sm">上传文件</h3>
		<Upload
			multiple
			type="drag"
			action="Upload"
			:default-file-list="[]"
			:before-upload="handleUpload"
			class="my-md"
		>
			<div class="py-lg">
				<Icon
					type="ios-cloud-upload"
					size="52"
					style="color: #3399ff"
				></Icon>
				<p>点击或者拖动文件到这里</p>
			</div>
		</Upload>

		<div
			class="demo-upload-list text-center"
			v-for="(item, index) in imgList"
			:key="index"
		>
			<template>
				<img
					:src="item.url"
					class="w-5xl h-4xl object-contain"
					v-show="/(\.jpeg|\.png|\.jpg|\.gif)$/i.test(item.url)"
				/>
				<video
					autoplay
					muted
					:src="item.url"
					class="w-5xl h-4xl object-contain"
					v-show="
						/(\.mp4|\.mov|\.rmvb|\.AVI|\.rm|\.FLV)$/i.test(item.url)
					"
				></video>
				<p>{{ item.url }}</p>
				<div class="demo-upload-list-cover"></div>
			</template>
		</div>
		<div class="flex ac sb margin padding">
			<h3><b>请设置nft名称</b><br /></h3>
			<p>
				<Input
					type="text"
					v-model="nftName"
					placeholder="请输入nft名称"
				/>
			</p>
		</div>
		<div class="flex ac sb margin padding">
			<h3><b>请设置nft简单介绍(最多100字)</b><br /></h3>
			<p>
				<Input
					type="textarea"
					v-model="nftDesc"
					placeholder="请输入nft简单介绍"
				/>
			</p>
		</div>

		<div class="px-xl my-lg">
			<Button
				type="primary"
				@click.native="create721Token"
				shape="circle"
				long
				size="large"
				class="margin"
				>发行NFT</Button
			>
		</div>
	</div>
</template>

<script>
import Web3 from 'web3';
import { NETWORKID, CONTRACTBUILD } from '@/config';
import { ststoken, getAuthorization, createNftInfo } from '@/api';
import OSS from 'ali-oss';
export default {
	data() {
		return {
			switch1: '',
			NETWORK_ID: NETWORKID,
			web3: Web3,
			// VRPressToken: '',
			myAddress: '',
			assets: [],
			nftName: '',
			nftDesc: '',
			imgList: [],
			objData: null,
			file: null,
		};
	},
	methods: {
		back() {
			window.history.go(-1);
		},
		change() {
			console.log('switchchange');
		},
		async create721Token() {
			console.log('test create');
			console.log('my address is' + this.myAddress);

			const contractData = require('../../../' +
				CONTRACTBUILD +
				'/contracts/AssetToken.json');
			const deployData = this.getDeployData();
			// const tokenProxyAdresses = deployData.proxies["marketplace/AssetToken"]
			const VRPressTokenAddress = deployData.contracts.AssetToken.address;
			const VRPressToken = await new this.web3.eth.Contract(
				contractData.abi,
				// tokenProxyAdresses[tokenProxyAdresses.length - 1].address
				VRPressTokenAddress
			);
			//请求合约发币
			var createRlt = 1;
			var createCallback = await VRPressToken.methods
				.mint(this.nftName, '/nfts/' + this.file.name, this.nftDesc) //todo 需换成页面传的参数 nft名称，nft资源路径
				.send(
					{
						from: this.myAddress,
						gas: 500000,
					},
					() => {
						console.log('trade is process');
						alert('nft 发行上链中。。。');
						this.$router.push('/myhome');
					}
				)
				.on('confirmation', () => {
					console.log('confirmation');
					// alert("nft 发行成功");
				})
				.catch(function(error) {
					console.log(error);
					createRlt = 0;
					alert('nft 发行失败！');
				});
			if (createRlt) {
				//同步信息到后端接口
				const totalSupply = await VRPressToken.methods
					.totalSupply()
					.call();
				// console.log(createCallback);
				let res4 = await createNftInfo({
					nft_address: VRPressTokenAddress,
					nft_id: parseInt(totalSupply) - 1,
					nft_name: this.nftName,
					nft_uri: '/nfts/' + this.file.name,
					nft_tag: '',
					nft_description: this.nftDesc,
					nft_type: '',
					txid: createCallback.transactionHash,
					lang: 'zh_CN',
				});
				if (res4.status == 200) {
					if (res4.data.code !== 0) {
						console.log('同步nft信息失败！');
					}
				} else {
					console.log('同步NFT信息失败！');
				}
			}
		},
		async getWeb3() {
			var web3;
			if (window.ethereum) {
				// Modern dapp browsers
				web3 = new Web3(window.ethereum);
				try {
					// metamaskが開いて権限許可を尋ねる
					await window.ethereum.enable();
				} catch (error) {
					// 拒否した場合に入ってくる
					console.log('denied');
				}
			} else if (window.web3) {
				// Legacy dapp browsers...
				web3 = new Web3(window.web3.currentProvider);
			} else {
				// this.selectedModal = this.MODALS.METAMASK
				// this.openModal({
				// 	title: "confirm",
				// 	isOnlyConfirm: true
				// })
			}

			web3 = new Web3(window.web3.currentProvider);
			return web3;
		},
		getDeployData() {
			return require(`../../../zos.dev-${this.NETWORK_ID}.json`);
		},

		async getStstoken() {
			let res = await ststoken(getAuthorization());
			// console.log(res.data.data.SecurityToken);
			let data = res.data.data;
			// console.log(data.SecurityToken);
			let client = new OSS({
				accessKeyId: 'LTAI4Fxv55cArEHyaNoK7L7b', //已经替换为+1的（√）
				accessKeySecret: 'fFVmSCAgySqhuVkdHz7nbAbWJ167DW', //需要替换为+1的（x）
				bucket: 'haichain-nfts',
				stsToken: data.SecurityToken,
				secure: true,
			});

			console.log(188, client);
			this.objData = data;
		},
		//上传文件
		Upload(file) {
			// console.log(file);
			let store = new OSS({
				accessKeyId: this.objData.AccessKeyId,
				accessKeySecret: this.objData.AccessKeySecret,
				bucket: 'haichain-nfts',
				stsToken: this.objData.SecurityToken,
				region: 'oss-cn-hangzhou',
				secure: true,
			});
			//let store = new OSS(this.objData);

			store
				.multipartUpload(
					//第一个参数可以设置自定义的路径
					'/nfts/' + file.name,
					// file.name,
					file,
					{
						//获取进度条的值
						progress: (p) => {
							console.log(p);
						},
					}
				)
				.then(
					//处理成功
					(result) => {
						//处理签名地址
						store.signatureUrl(result.name);
						// console.log(result);
						this.imgList.push({
							name: result.name,
							url: result.res.requestUrls[0].split('?')[0],
						});
					}
				)
				.catch((err) => {
					console.log(err);
				});
		},
		handleUpload(file) {
			this.file = file;
			this.Upload(file);
			return false;
		},
	},
	async mounted() {
		// console.log(ststoken);
		// console.log(OSS);
		this.getStstoken();

		this.web3 = await this.getWeb3();
		await this.web3.eth.getAccounts((error, accounts) => {
			if (error) {
				console.log('error');
				return;
			}
			this.myAddress = accounts[0];
			console.log('my address is' + this.myAddress);
		});
	},
};
</script>
